package com.sawyerqiu.ui;

import com.sawyerqiu.model.Result;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.function.Consumer;
import java.util.function.Function;

public class MainUi {

    private JFrame mainFrame;

    /////
    private JPanel outputOrderPanel;
    ////
    private JPanel insertPanel;


    public MainUi() {
        mainFrame = new JFrame("工具");

        initOutPutOrderPanel();
        initInsertPanel();

        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setSize(400, 680);

        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, outputOrderPanel, insertPanel);
        splitPane.setResizeWeight(0.75);

        mainFrame.add(splitPane);
        mainFrame.setVisible(true);
    }

    private void initInsertPanel() {
        insertPanel = new InputDataPanel();
    }

    private void initOutPutOrderPanel() {
        outputOrderPanel = new OrderOutputPanel();
    }


    public static void addFileChooserAction(JButton button, Function<File, Result> fileCheck, Consumer<File> consumer) {
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser jfc = new JFileChooser();
                jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                jfc.showDialog(new JLabel(), "选择");
                File file = jfc.getSelectedFile();

                if (file == null) {
                    JOptionPane.showMessageDialog(null,
                            "请选择正确的文件", "warn", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                Result res = fileCheck.apply(file);
                if (res.isFail()) {
                    JOptionPane.showMessageDialog(null,
                            res.getTip(), "warn", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                consumer.accept(file);
            }
        });
    }
}
